import { PAGE_NUM, PAGE_SIZE } from '@/lib/constants';
import { z } from 'zod';

export const pageSchema = z.object({
  page: z.coerce.number().int().positive().optional().default(PAGE_NUM),
  pageSize: z.coerce
    .number()
    .int()
    .positive()
    .max(30)
    .optional()
    .default(PAGE_SIZE),
});

export const jsonToDateRangeSchema = z
  .string()
  .refine((v) => {
    try {
      const res = JSON.parse(v);
      if (!res.from) return false;
      if (Number.isNaN(new Date(res.from).getTime())) return false;
      if (res.to && Number.isNaN(new Date(res.to).getTime())) return false;
      return true;
    } catch (error) {
      return false;
    }
  })
  .transform((v) => {
    const res = JSON.parse(v);
    res.from = new Date(res.from);
    res.to = res.to ? new Date(res.to) : undefined;
    return res as { from: Date; to?: Date };
  })
  .optional();

export const getJsonToEnumArraySchema = <T extends readonly string[]>(
  enumValues: T,
) => {
  return z
    .string()
    .refine((v) => {
      try {
        const res = JSON.parse(v);
        if (!Array.isArray(res)) return false;
        for (const status of res)
          if (!enumValues.includes(status)) return false;
        return true;
      } catch (error) {
        return false;
      }
    })
    .transform((v) => JSON.parse(v) as (typeof enumValues)[number][])
    .optional();
};
